package com.msh.platform.elm.service.impl;

import com.msh.platform.bizmedia.base.util.Tools;
import com.msh.platform.elm.common.constants.Constants;
import com.msh.platform.elm.common.util.MD5;
import com.msh.platform.elm.dao.SellerRepository;
import com.msh.platform.elm.dao.UserAcctRepository;
import com.msh.platform.elm.entity.SellerInfo;
import com.msh.platform.elm.entity.UserAcct;
import com.msh.platform.elm.service.SellerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SellerServiceImpl implements SellerService {

    @Autowired
    private SellerRepository sellerRepository;
    @Autowired
    private UserAcctRepository userAcctRepository;
    
    @Transactional
    public void saveSellerAndAcct(SellerInfo seller) {
    	Integer currTime = Tools.getCurrTime();
        
        String encPwdString = MD5.compile(seller.getPasswd() + Constants.PWD_MD5_KEY);
        seller.setPasswd(encPwdString);
        seller.setStatus("0");
		seller.setDelFlag("0");
        seller.setCreateTime(currTime);
        int sellerId = sellerRepository.save(seller).getId();
        
        //生成商会账户
        UserAcct acct = new UserAcct();
        acct.setUserId(sellerId);
        acct.setUserType("0");  //商会用户
        acct.setBalVal(new BigDecimal(0));
        acct.setBonus(new BigDecimal(0));
        acct.setStatus("0");
        acct.setCreateTime(currTime);
        acct.setUpdateTime(currTime);
        userAcctRepository.save(acct);
        if (log.isDebugEnabled()) {
            log.debug("保存商会用户跟账户成功");
        }
    }
    
    public void save(SellerInfo seller) {
    	sellerRepository.save(seller);
    }

    public SellerInfo getSeller(String phone,String password) {
        SellerInfo seller = sellerRepository.findByPhoneAndPasswd(phone,password);
        return seller;
    }
    
    public SellerInfo findByPhone(String phone) {
        SellerInfo seller = sellerRepository.findByPhone(phone);
        return seller;
    }
    
    public Page<SellerInfo> findAll(Pageable pageable){
    	return sellerRepository.findAll(pageable);
    }
    
    public SellerInfo getSeller(int id) {
        SellerInfo seller = sellerRepository.getOne(id);
        return seller;
    }
    
    public Page<SellerInfo> findByStatus(String status,Pageable pageable){
    	return sellerRepository.findByStatus(status, pageable);
    }
    
    public List<SellerInfo> findAllById(ArrayList<Integer> ids){
    	return sellerRepository.findAllById(ids);
    }

}
